<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <!-- @clear 点击input的叉号进行触发重新发请求获取原来的数据 -->
    <el-card class="box-card">
      <div class="user_card">
        <el-input
          placeholder="请输入内容"
          class="input-with-select"
          v-model="queryInfo.query"
          @input="getUserList"
          :clearable="true"
          @clear="getUserList"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserList"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="dialogVisible = true"
          >添加用户</el-button
        >
      </div>
      <!-- 用户列表数据 stripe隔行变色-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号" width="100px">
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- @change  switch 状态发生变化时的回调函数 -->`
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- :page-size="100" 每页显示条数 -->
      <!-- :total="400" 共多少条-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[4, 8, 12, 20]"
        :page-size="4"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="closeDialog"
      >
        <span>
          <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <!-- 别管取消还是确定 都是关闭el-dialog 只要el-dialog关闭就清除input输入框的内容 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editdialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="editclose"
      >
        <span>
          <!-- :rules="editruleFormRef" -->
          <el-form
            :model="editForm"
            :rules="editruleFormRef"
            ref="editruleFormRef"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editsubmit(editruleFormRef.id)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    //   验证邮箱的校验规则
    var validateEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的校验规则
    var validateMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    // 修改用户信息的验证规则:
    var checkoutemail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    var checkoutemobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      // 每页显示条数pagesize   当前页码pagenum
      queryInfo: { query: "", pagenum: 1, pagesize: 4 },
      userList: [],
      // 一共多少条数据
      total: 0,
      //:current-page="currentPage4"当前选中的页数
      currentPage4: 1,
      //   控制添加用户对话框的显示和隐藏
      dialogVisible: false,
      //   控制修改用户信息的对话框
      editdialogVisible: false,
      //   添加用户的表单
      form: { username: "", password: "", email: "", mobile: "" },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ]
      },
      //   修改用户的数据
      editForm: [],
      //   修改用户的验证规则
      editruleFormRef: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkoutemail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkoutemobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },

  methods: {
    //   获取用户数据
    async getUserList() {
      const { data } = await this.$http.get("/users", {
        params: this.queryInfo
      });
      console.log(data);
      if (data.meta.status !== 200) return this.$message.err("获取数据失败");
      this.userList = data.data.users;
      this.total = data.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
      console.log(`当前页: ${val}`);
    },
    // switch 状态发生变化时的回调函数
    async userStatusChange(userinfo) {
      const { data } = await this.$http.put(
        `/users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (data.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
      console.log(data);
    },
    // 添加用户,修改用户关闭对话框之前触发
    handleClose(done) {
      this.$confirm("确认关闭?")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    closeDialog() {
      this.$refs.form.resetFields();
    },
    // 添加用户点击确定进行预校验
    addUser() {
      this.$refs.form.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        // 发送网络请求添加数据
        const { data } = await this.$http.post("/users", this.form);
        if (data.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        // 隐藏弹出添加用户框
        this.dialogVisible = false;
        // 重新发送请求获取添加后新的数据
        this.getUserList();
      });
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      console.log(id);
      const { data } = await this.$http.get("/users/" + id);
      if (data.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      console.log(data);
      this.editForm = data.data;
      // 显示弹出框
      this.editdialogVisible = true;
    },
    // 关闭编辑用户的对话框
    editclose() {
      this.$refs.editruleFormRef.resetFields();
    },
    // 提交编辑用户信息
    editsubmit() {
      this.$refs.editruleFormRef.validate(async valid => {
        if (!valid) return this.$message.error("信息格式错误");
        // 发送请求
        const { data } = await this.$http.put("/users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        if (data.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("修改成功");
        // 修改成功后关闭对话框
        this.editdialogVisible = false;
        // 发送请求获取修改后最新的数据
        this.getUserList();
        console.log(data);
      });
    },
    async removeUserById(id) {
      const dataremove = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (dataremove !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data } = await this.$http.delete("/users/" + id);
      if (data.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserList();
      console.log(data);
    }
  }
};
</script>
<style lang="less" scope>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  .user_card {
    display: flex;
    .el-input {
      width: 40%;
      margin-right: 20px;
    }
  }
  .el-table {
    margin-top: 20px;
  }
}
</style>